package com.ddtech.business.room.service.impl;

import com.ddtech.business.common.BaseService;
import com.ddtech.business.room.dto.RoomUserDTO;
import com.ddtech.business.room.entity.Room;
import com.ddtech.business.room.entity.RoomUser;
import com.ddtech.business.room.mapper.RoomUserMapper;
import com.ddtech.business.room.service.RoomService;
import com.ddtech.business.room.service.RoomUserService;
import com.ddtech.exception.BadRequestException;
import com.ddtech.utils.SecurityUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @version v1.0
 * @ClassName:RoomUserServiceImpl description：
 * @author:wei_zhang(xiao)
 * @date: 2024-11-18 20:17
 */
@Service
public class RoomUserServiceImpl extends BaseService<RoomUserMapper, RoomUser>  implements RoomUserService {

    @Autowired
    private RoomService roomService;

    @Resource
    private RoomUserMapper roomUserMapper;

    @Resource
    private RedissonClient redissonClient;


    private static final Lock globalLock= new ReentrantLock(true);


    @Override
    public void joinRoom(RoomUser roomUser) {
        //获取锁(可重入)，指定锁的名称
        RLock lock = redissonClient.getLock("joinRoomLock");
        //尝试获取锁，参数分别是：获取锁的最大等待时间(期间会重试)，锁自动释放时间，时间单位
        boolean isLock = false;
        try {
            isLock = lock.tryLock(1,5, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
            throw new BadRequestException("当前人数太多，请重试加入房间。");
        }
        //判断获取锁成功
        if(isLock){
            try{
                Room room = roomService.getById(roomUser.getRoomId());
                int totalNumber =room.getParticipantPopulation();
                if(room.getStatus()==1){
                    throw new BadRequestException("该房间已开始，请选择其他房间加入。");
                }
                RoomUserDTO roomUserDTO =   roomUserMapper.getHadJoinRoomUser(roomUser.getRoomId());
                //人数相等，不允许加入
                if(totalNumber==roomUserDTO.getHadJoinRoomUser()){
                    throw new BadRequestException("该房间人员已满，不可进入。");
                }
                roomUser.init();
                roomUser.setUserId(SecurityUtils.getUserId());
                roomUser.setUserName(SecurityUtils.getName());
                roomUser.setStatus(0);
                this.saveOrUpdate(roomUser);
            }finally{
                //释放锁
                lock.unlock();
            }
        }
    }



//    @Override
//    public void joinRoom(RoomUser roomUser) {
//        Room room = roomService.getById(roomUser.getRoomId());
//        int totalNumber =room.getParticipantPopulation();
//        //synchronized (roomUser.getUserId()){
//        if(room.getStatus()==1){
//            throw new BadRequestException("该房间已开始，请选择其他房间加入。");
//        }
//        globalLock.lock();
//        try{
//            RoomUserDTO roomUserDTO =   roomUserMapper.getHadJoinRoomUser(roomUser.getRoomId());
//            //人数相等，不允许加入
//            if(totalNumber==roomUserDTO.getHadJoinRoomUser()){
//                throw new BadRequestException("该房间人员已满，不可进入。");
//            }
//            roomUser.init();
//            roomUser.setUserId(SecurityUtils.getUserId());
//            roomUser.setUserName(SecurityUtils.getName());
//            roomUser.setStatus(0);
//            this.saveOrUpdate(roomUser);
//        }catch(Exception e){
//            throw new BadRequestException("该房间人员已满，不可进入。");
//        }finally {
//            globalLock.unlock();
//        }
//       // }
//    }
}
